import _regeneratorRuntime from "@babel/runtime/regenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _omit from "lodash/omit";
import _isNumber from "lodash/isNumber";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
import _isNil from "lodash/isNil";
var _excluded = ["lovCode", "editable", "fieldCode", "fieldName", "numberMax", "numberMin", "numberPrecision", "dateFormat", "bucketName", "bucketDirectory", "areaMaxLine", "fieldType", "linkTitle", "linkHref", "linkNewWindow", "lovMappings", "dataSource", "paramList", "defaultValue", "defaultValueMeaning", "isGrid", "placeholder", "getValueFromCache"],
    _excluded2 = ["initialValue", "initialMeaning"],
    _excluded3 = ["getValueFromCache", "currentUnitCode", "isGrid", "code", "isGridVisible"];

/* eslint-disable eqeqeq */

/**
 * 个性化组件utils工具包
 * @date: 2019-12-15
 */
import React from 'react';
import { Form, Input, InputNumber } from 'antd'; // import { groupBy, isNil, isArray, isEmpty } from 'lodash';

import moment from 'moment';
import TLEditor from "../../TLEditor";
import Upload from "../../Upload";
import intl from "../../../utils/intl";
import { yesOrNoRender, numberRender } from "../../../utils/renderer";
import request from "../../../utils/request";
import { getEnvConfig } from "../../../utils/iocUtils";
import { getCurrentOrganizationId, getResponse, getUserOrganizationId } from "../../../utils/utils";
import { DEFAULT_DATE_FORMAT } from "../../../utils/constants";
import template from "../../../utils/template";
import { FlexSelect, // FlexRadioGroup,
FlexLov, FlexDatePicker, FlexCheckbox, FlexSwitch, FlexLink } from "./FlexComponents";
import LovMulti from "./LovMulti";
// FormItem组件初始化
var FormItem = Form.Item;

var _getEnvConfig = getEnvConfig(),
    CPAAS_PLATFORM = _getEnvConfig.CPAAS_PLATFORM;
/* 接口部分 */
// const mockapi = '/api/cpfm';


export function queryCode() {
  return _queryCode.apply(this, arguments);
}

function _queryCode() {
  _queryCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var params,
        _args = arguments;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            params = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            _context.t0 = getResponse;
            _context.next = 4;
            return request("".concat(CPAAS_PLATFORM, "/v1/lovs/value"), {
              query: params
            });

          case 4:
            _context.t1 = _context.sent;

            _context.t2 = function () {};

            return _context.abrupt("return", (0, _context.t0)(_context.t1, _context.t2));

          case 7:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _queryCode.apply(this, arguments);
}

export function queryUnitCustConfig() {
  return _queryUnitCustConfig.apply(this, arguments);
}
/**
 * 对拿到数据做进一步的渲染适配
 * @param renderOptions 渲染类别
 */

function _queryUnitCustConfig() {
  _queryUnitCustConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var params,
        _args2 = arguments;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            params = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {};
            _context2.t0 = getResponse;
            _context2.next = 4;
            return request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/ui-customize"), {
              query: params,
              method: 'GET'
            });

          case 4:
            _context2.t1 = _context2.sent;

            _context2.t2 = function () {};

            return _context2.abrupt("return", (0, _context2.t0)(_context2.t1, _context2.t2));

          case 7:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _queryUnitCustConfig.apply(this, arguments);
}

export function getRender(fieldType) {
  var componentProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  switch (fieldType) {
    case 'SWITCH':
    case 'CHECKBOX':
      return function (val) {
        return yesOrNoRender(Number(val));
      };

    case 'INPUT_NUMBER':
      return _isNil(componentProps.precision) ? function (val) {
        return val;
      } : function (val) {
        return numberRender(val, componentProps.precision || 0, true, true);
      };

    case 'DATE_PICKER':
      return function (val) {
        return val && moment(val).format(componentProps.format);
      };

    default:
      return function (val) {
        return val;
      };
  }
}
export function getValuePropName(type) {
  if (type === 'UPLOAD') return 'attachmentUUID';
  if (type === 'CHECKBOX' || type === 'SWITCH') return 'checked';
  return 'value';
}
export function customizeFormOptions(options) {
  var _ref = options || {},
      fieldType = _ref.fieldType,
      _ref$dateFormat = _ref.dateFormat,
      dateFormat = _ref$dateFormat === void 0 ? '' : _ref$dateFormat,
      initialValue = _ref.initialValue;

  var rules = customizeFormRules(options);
  var formOptions = {
    rules: rules,
    valuePropName: getValuePropName(fieldType),
    initialValue: initialValue
  }; // if(fieldType === 'RADIO_GROUP'){
  //   formOptions.getValueProps = e => (e||{target: {}}).target.value;
  //   formOptions.getValueFromEvent = e => {
  //     return e.target.value;
  //   };
  // }

  if (fieldType === 'DATE_PICKER') {
    // const onlyDateFormat = dateFormat.match(/(^\S+DD)/) || ['YYYY/MM/DD'];
    var newDateFormat = /HH|hh|mm|ss/.test(dateFormat) ? dateFormat : "".concat(DEFAULT_DATE_FORMAT, " 00:00:00");

    formOptions.getValueProps = function (dateStr) {
      return {
        value: dateStr ? moment(dateStr, newDateFormat) : dateStr
      };
    };

    formOptions.getValueFromEvent = function (e) {
      if (!e || !e.target) {
        return e && e.format ? e.format(newDateFormat) : e;
      }

      var target = e.target;
      return target.type === 'checkbox' ? target.checked : target.value;
    };
  }

  return formOptions;
}
export function parseContentProps(contentProps, code) {
  var _ref2 = contentProps || {},
      lovCode = _ref2.lovCode,
      editable = _ref2.editable,
      fieldCode = _ref2.fieldCode,
      fieldName = _ref2.fieldName,
      numberMax = _ref2.numberMax,
      numberMin = _ref2.numberMin,
      numberPrecision = _ref2.numberPrecision,
      _ref2$dateFormat = _ref2.dateFormat,
      dateFormat = _ref2$dateFormat === void 0 ? '' : _ref2$dateFormat,
      bucketName = _ref2.bucketName,
      bucketDirectory = _ref2.bucketDirectory,
      areaMaxLine = _ref2.areaMaxLine,
      fieldType = _ref2.fieldType,
      linkTitle = _ref2.linkTitle,
      linkHref = _ref2.linkHref,
      linkNewWindow = _ref2.linkNewWindow,
      lovMappings = _ref2.lovMappings,
      _ref2$dataSource = _ref2.dataSource,
      dataSource = _ref2$dataSource === void 0 ? {} : _ref2$dataSource,
      _ref2$paramList = _ref2.paramList,
      paramList = _ref2$paramList === void 0 ? [] : _ref2$paramList,
      defaultValue = _ref2.defaultValue,
      defaultValueMeaning = _ref2.defaultValueMeaning,
      isGrid = _ref2.isGrid,
      placeholder = _ref2.placeholder,
      getValueFromCache = _ref2.getValueFromCache,
      rest = _objectWithoutProperties(_ref2, _excluded);

  var disabled = editable === 0;
  var value = dataSource[fieldCode];
  var meaning = dataSource["".concat(fieldCode, "Meaning")];

  if (_isNil(value)) {
    value = defaultValue;
    meaning = defaultValueMeaning;
  }

  if (!_isNil(meaning)) {
    meaning = typeof meaning === 'object' ? Object.values(meaning).join('/') : meaning;
  } else {
    meaning = value;
  }

  var commonProps = _objectSpread({
    initialValue: preAdapterInitValue(fieldType, value),
    initialMeaning: meaning,
    placeholder: placeholder,
    disabled: disabled,
    dataSource: dataSource
  }, _omit(rest, ['conditionHeaderDTOs', 'renderOptions', 'required', 'visible', 'standardField', 'isStandardField']));

  var tempProps = {};

  if (fieldType === 'TEXT_AREA') {
    tempProps = {
      rows: areaMaxLine || 2
    };
  }

  if (fieldType === 'INPUT_NUMBER') {
    tempProps = {
      max: numberMax,
      min: numberMin,
      precision: numberPrecision || 0
    };
  }

  if (fieldType === 'DATE_PICKER') {
    tempProps = {
      fieldCode: fieldCode,
      showTime: /HH|hh|mm|ss/.test(dateFormat),
      format: dateFormat
    };
  }

  if (fieldType === 'LOV') {
    tempProps = {
      code: lovCode,
      lovMappings: lovMappings,
      textValue: meaning,
      queryParams: getContextParams(paramList, {
        code: code,
        getValueFromCache: getValueFromCache,
        isGrid: isGrid,
        form: rest.form,
        dataSource: dataSource
      })
    };

    if (rest.multipleFlag) {
      delete tempProps.lovMappings;
      tempProps.translateData = tempProps.textValue;
      delete tempProps.textValue;
    }
  }

  if (fieldType === 'TL_EDITOR') {
    tempProps = {
      label: fieldName,
      field: fieldCode,
      token: dataSource._token
    };
  }

  if (fieldType === 'UPLOAD') {
    tempProps = {
      label: fieldName,
      field: fieldCode,
      viewOnly: disabled,
      bucketName: bucketName,
      bucketDirectory: bucketDirectory
    };
    delete commonProps.disabled;
  }

  if (fieldType === 'LINK') {
    tempProps = {
      linkTitle: linkTitle,
      linkHref: linkHref,
      linkNewWindow: linkNewWindow,
      form: rest.form,
      dataSource: dataSource
    };
  }

  if (fieldType === 'SELECT') {
    tempProps = {
      lovCode: lovCode,
      lovMappings: lovMappings,
      fieldCode: fieldCode,
      params: getContextParams(paramList, {
        getValueFromCache: getValueFromCache,
        isGrid: isGrid,
        code: code,
        form: rest.form,
        dataSource: dataSource
      })
    };
  } // eslint-disable-next-line no-param-reassign


  if (fieldType === 'SWITCH') delete commonProps.style;
  return _objectSpread(_objectSpread({}, commonProps), tempProps);
}
/**
 * 根据类型参数生成不同的表单组件
 * @param type 组件类型
 */

export function getFormItemComponent(fieldType, renderOptions, code) {
  var Component;

  switch (fieldType) {
    case 'INPUT':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(Input, props);
      };

      break;

    case 'INPUT_NUMBER':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(InputNumber, props);
      };

      break;

    case 'SELECT':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(FlexSelect, props);
      };

      break;
    // case 'RADIO_GROUP':
    //   Component = props => <FlexRadioGroup {...props} />;
    //   break;

    case 'CHECKBOX':
      Component = FlexCheckbox;
      break;

    case 'SWITCH':
      Component = FlexSwitch;
      break;

    case 'LOV':
      Component = FlexLov;
      break;

    case 'DATE_PICKER':
      Component = FlexDatePicker;
      break;

    case 'UPLOAD':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(Upload, props);
      };

      break;

    case 'TL_EDITOR':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(TLEditor, props);
      };

      break;

    case 'TEXT_AREA':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(Input.TextArea, props);
      };

      break;

    case 'LINK':
      Component = FlexLink;
      break;

    default:
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(Input, props);
      };

  }

  return function (options) {
    var form = options.form,
        _options$isEdit = options.isEdit,
        isEdit = _options$isEdit === void 0 ? true : _options$isEdit,
        readOnly = options.readOnly,
        wrapProps = options.wrapProps,
        contentProps = options.contentProps,
        fieldCode = options.fieldCode,
        _options$formOptions = options.formOptions,
        formOptions = _options$formOptions === void 0 ? {} : _options$formOptions;
    var viewOnly = !isEdit || readOnly || renderOptions !== 'WIDGET' || !form;
    var hasFormDec = !viewOnly;
    contentProps.form = form;

    var _parseContentProps = parseContentProps(contentProps, code),
        initialValue = _parseContentProps.initialValue,
        initialMeaning = _parseContentProps.initialMeaning,
        componentProps = _objectWithoutProperties(_parseContentProps, _excluded2);

    var values = componentProps.dataSource; // 只读单元不需要用form中的值覆盖

    if (hasFormDec) {
      values = _objectSpread(_objectSpread({}, values), form && form.getFieldsValue());
    }

    var newValue = preAdapterInitValue(fieldType, values[fieldCode]);
    var newMeaning = initialMeaning;

    if (newValue !== initialValue) {
      newMeaning = newValue;
    }

    var newFormOptions = customizeFormOptions(_objectSpread(_objectSpread({}, formOptions), {}, {
      initialValue: initialValue
    }));
    var component = Component(componentProps);
    var forceUseComponent = false;

    if (contentProps.multipleFlag && fieldType === 'LOV') {
      component = /*#__PURE__*/React.createElement(LovMulti, Object.assign({}, componentProps, {
        viewOnly: viewOnly
      }));
      forceUseComponent = true;
    }

    if (fieldType === 'UPLOAD' || fieldType === 'LINK') {
      forceUseComponent = true;
    } // 调整component


    if (hasFormDec) {
      component = form.getFieldDecorator(fieldCode, newFormOptions)(component);
    } else if (!forceUseComponent) {
      var renderText = getRender(fieldType, componentProps)(fieldType === 'LOV' || fieldType === 'SELECT' ? newMeaning : newValue);
      component = /*#__PURE__*/React.createElement("span", null, renderText);
    } else {
      component.props.value = initialValue;
    }

    return isEdit ? /*#__PURE__*/React.createElement(FormItem, wrapProps, component) : component;
  };
}
/**
 * 对initialValue进行预处理
 * @param type 处理类型
 * @param value 表单值
 */

export function preAdapterInitValue(type, value) {
  switch (type) {
    case 'CHECKBOX':
    case 'SWITCH':
      // eslint-disable-next-line eqeqeq
      return _isNil(value) ? value : Number(value);

    default:
      return value;
  }
}
/**
 * 标准字段（预定义）应用个性化样式
 * @param individual 个性化配置信息
 * @param item 存有标准字段formItem及其配置信息的对象
 * @param targetRows 解析后存储的目标对象
 * @param {Object} object 解析配置、包含{maxCol、form、tempRowBase}
 */

export function adapterStandardFormIndividual(individualProps, item) {
  var targetRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  var _ref3 = arguments.length > 3 ? arguments[3] : undefined,
      baseCol = _ref3.baseCol,
      form = _ref3.form,
      unitLabelCol = _ref3.unitLabelCol,
      unitWrapperCol = _ref3.unitWrapperCol,
      dataSource = _ref3.dataSource,
      tempItems = _ref3.tempItems;

  var parseRows = targetRows;
  var formItem = item.formItem,
      rowProps = item.rowProps,
      colProps = item.colProps;
  var rules = customizeFormRules(individualProps);
  var _individualProps$form = individualProps.formRow,
      formRow = _individualProps$form === void 0 ? item.row : _individualProps$form,
      _individualProps$form2 = individualProps.formCol,
      formCol = _individualProps$form2 === void 0 ? item.col : _individualProps$form2,
      visible = individualProps.visible,
      labelCol = individualProps.labelCol,
      wrapperCol = individualProps.wrapperCol,
      defaultValue = individualProps.defaultValue,
      fieldType = individualProps.fieldType,
      _individualProps$colS = individualProps.colSpan,
      colSpan = _individualProps$colS === void 0 ? 1 : _individualProps$colS;
  if (visible === 0 || _isNil(item.row)) return; // const newRowProps = { ...rowProps, ..._rowProps };

  var newColProps = _objectSpread({}, colProps);

  if ((rowProps.className || '').indexOf('half-row') > -1) {
    newColProps.span = 12;
  } else {
    newColProps.span = colSpan * baseCol;
  }

  adjustRowAndCol(parseRows, formItem, {
    row: formRow,
    col: formCol,
    tempItems: tempItems,
    rowProps: rowProps,
    colProps: newColProps
  });
  formItem.props.labelCol = {
    span: labelCol || unitLabelCol
  };
  formItem.props.wrapperCol = {
    span: wrapperCol || unitWrapperCol
  };
  traversalFormItems(formItem, _objectSpread(_objectSpread({}, individualProps), {}, {
    defaultValue: preAdapterInitValue(fieldType, defaultValue),
    rules: rules,
    form: form,
    dataSource: dataSource
  }));
}
/**
 * 用于调整FormItem类型的react-element对象的配置
 * @param {object} individual 个性化配置属性
 */

export function customizeFormRules(individual) {
  var _ref4 = individual || {},
      textMaxLength = _ref4.textMaxLength,
      textMinLength = _ref4.textMinLength,
      required = _ref4.required,
      fieldName = _ref4.fieldName,
      _ref4$selfRules = _ref4.selfRules,
      selfRules = _ref4$selfRules === void 0 ? {} : _ref4$selfRules;

  var rules = [];

  if (textMaxLength !== -1 && textMaxLength !== undefined) {
    rules.push({
      max: textMaxLength,
      message: intl.get('cpaas.common.validation.max', {
        max: textMaxLength
      })
    });
  }

  if (textMinLength !== -1 && textMinLength !== undefined) {
    rules.push({
      min: textMinLength,
      message: intl.get('cpaas.common.validation.min', {
        min: textMinLength
      })
    });
  }

  if (required !== -1 && required !== undefined) {
    rules.push({
      required: !!required,
      message: intl.get('cpaas.common.validation.notNull', {
        name: fieldName
      })
    });
  }

  if (selfRules.validator) {
    rules.push(selfRules);
  }

  return rules;
}
/**
 * 调整FormItem的行列结构
 * @param targetRows 原存储FormItem行列信息的对象，key为行数
 * @param formItem 插入的表单项
 * @param Object 配置对象
 */

export function adjustRowAndCol() {
  var targetRows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var formItem = arguments.length > 1 ? arguments[1] : undefined;

  var _ref5 = arguments.length > 2 ? arguments[2] : undefined,
      row = _ref5.row,
      col = _ref5.col,
      rowProps = _ref5.rowProps,
      colProps = _ref5.colProps,
      tempItems = _ref5.tempItems;

  var newRow = row - 1;
  var newCol = col - 1;

  if (row === undefined || col === undefined || !_isNumber(newRow) || !_isNumber(newCol)) {
    tempItems.push({
      formItem: formItem,
      rowProps: rowProps,
      colProps: colProps
    });
    return;
  }

  var parseRows = targetRows; // 如果被检测行不存在，会在targetRows中初始化一个行

  if (!parseRows[newRow]) {
    parseRows[newRow] = {
      rowProps: {},
      formItemList: []
    };
  }

  if (parseRows[newRow].formItemList[newCol]) {
    tempItems.push({
      formItem: formItem,
      rowProps: rowProps,
      colProps: colProps
    });
    return;
  }

  parseRows[newRow].rowProps = rowProps;
  parseRows[newRow].formItemList[newCol] = {
    colProps: colProps,
    formItem: formItem
  };
}
/**
 * 使用新规则替换FormItem原有的校验规则
 * @param formItem FormItem的reactElement
 * @param rules 新的规则项
 */

export function traversalFormItems() {
  var formItem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var fieldConfig = arguments.length > 1 ? arguments[1] : undefined;

  var _ref6 = fieldConfig || {},
      fieldName = _ref6.fieldName;

  var children = formItem && formItem.props ? formItem.props.children : null;

  if (children) {
    if (!_isNil(fieldName)) {
      // eslint-disable-next-line no-param-reassign
      formItem.props.label = fieldName;
    }

    if (_isArray(children)) {
      for (var i = 0; i < children.length; i++) {
        if (_isNil(children[i])) {
          return;
        }

        var props = children[i].props;
        mergeFormItemIndividual(props, fieldConfig); // if (props && props['data-__meta']) {
        //   return;
        // }
      }
    } else {
      var _props = children.props;
      mergeFormItemIndividual(_props, fieldConfig);
    }
  }
}

function mergeFormItemIndividual(props, fieldConfig) {
  var rules = fieldConfig.rules,
      _fieldConfig$lovMappi = fieldConfig.lovMappings,
      lovMappings = _fieldConfig$lovMappi === void 0 ? [] : _fieldConfig$lovMappi,
      form = fieldConfig.form,
      editable = fieldConfig.editable,
      defaultValue = fieldConfig.defaultValue,
      _fieldConfig$paramLis = fieldConfig.paramList,
      paramList = _fieldConfig$paramLis === void 0 ? [] : _fieldConfig$paramLis,
      numberPrecision = fieldConfig.numberPrecision,
      defaultValueMeaning = fieldConfig.defaultValueMeaning,
      _fieldConfig$dataSour = fieldConfig.dataSource,
      dataSource = _fieldConfig$dataSour === void 0 ? {} : _fieldConfig$dataSour,
      fieldType = fieldConfig.fieldType,
      multipleFlag = fieldConfig.multipleFlag,
      placeholder = fieldConfig.placeholder;
  var newRulesCollection = {
    others: [],
    required: false,
    max: false,
    min: false
  };
  var newProps = props;

  if (newProps && newProps['data-__meta']) {
    var _newProps$data__meta = newProps['data-__meta'],
        initialValue = _newProps$data__meta.initialValue,
        _newProps$data__meta$ = _newProps$data__meta.rules,
        oldRules = _newProps$data__meta$ === void 0 ? [] : _newProps$data__meta$;
    var name = newProps['data-__meta'].name;

    if (!_isEmpty(rules)) {
      oldRules.forEach(function (k, index) {
        if (k.required !== undefined) {
          newRulesCollection.required = oldRules[index];
        } else if (k.max !== undefined) {
          newRulesCollection.max = oldRules[index];
        } else if (k.min !== undefined) {
          newRulesCollection.min = oldRules[index];
        } else if (!k.customize) {
          newRulesCollection.others.push(oldRules[index]);
        }
      });
      rules.forEach(function (k, index) {
        if (k.required !== undefined) {
          newRulesCollection.required = rules[index];
        } else if (k.max !== undefined) {
          newRulesCollection.max = rules[index];
        } else if (k.min !== undefined) {
          newRulesCollection.min = rules[index];
        } else {
          newRulesCollection.others.push(rules[index]);
        }
      });
      var required = newRulesCollection.required,
          max = newRulesCollection.max,
          min = newRulesCollection.min,
          others = newRulesCollection.others;
      var newRules = [required, max, min].concat(_toConsumableArray(others)).filter(Boolean);
      newProps['data-__meta'].rules = newRules;
      newProps['data-__meta'].validate = [{
        rules: newRules,
        trigger: ['onChange']
      }];
    }

    if (lovMappings.length > 0) {
      var oldOnChange = newProps.onChange;

      newProps.onChange = function (val, record) {
        var newFields = lovMappings.reduce(function (prev, cur) {
          return _objectSpread(_objectSpread({}, prev), {}, _defineProperty({}, cur.targetCode, record[cur.sourceCode]));
        }, {});
        form.setFieldsValue(newFields); // eslint-disable-next-line no-unused-expressions

        for (var _len = arguments.length, others = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          others[_key - 2] = arguments[_key];
        }

        oldOnChange && oldOnChange.apply(void 0, [val, record].concat(others));
      };
    }

    if (_isNil(newProps['data-__field'].value) && !_isNil(defaultValue) && defaultValue != initialValue && _isNil(dataSource[name])) {
      newProps['data-__meta'].initialValue = defaultValue;
      newProps.value = defaultValue;

      if (fieldType === 'LOV' && multipleFlag === 1) {
        newProps.translateData = defaultValueMeaning;
      } else if (fieldType === 'LOV') {
        newProps.textValue = _isNil(defaultValueMeaning) ? defaultValue : defaultValueMeaning;
      }
    }

    if (paramList && paramList.length > 0) {
      newProps.queryParams = getContextParams(paramList);
    }

    if (typeof placeholder === 'string' && placeholder !== '') {
      newProps.placeholder = placeholder;
    } // eslint-disable-next-line no-unused-expressions


    editable !== -1 && !_isNil(editable) && (newProps.disabled = !editable); // eslint-disable-next-line no-unused-expressions

    !_isNil(numberPrecision) && (newProps.precision = numberPrecision);
  }
}

export function coverConfig(originConfig) {
  var conditions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var config = arguments.length > 2 ? arguments[2] : undefined;
  var newConfig = originConfig;
  conditions.forEach(function (i) {
    var _i$conExpression = i.conExpression,
        conExpression = _i$conExpression === void 0 ? '' : _i$conExpression;

    if (conExpression !== '') {
      var isErr = isErrConExpression(conExpression);

      if (!isErr) {
        var conNoReg = /(\d+)/g;
        var result = calculateExpression(i.lines || [], config);
        conExpression = conExpression.replace(conNoReg, function (_, m) {
          return result[m] || false;
        });
        conExpression = conExpression.replace(/AND/g, '&&').replace(/OR/g, '||'); // eslint-disable-next-line no-new-func

        newConfig[i.conType] = new Function("return ".concat(conExpression, ";"))() ? 1 : 0;
      }
    }
  });
  return newConfig;
}

function isErrConExpression(exp) {
  var leftBracketNum = (exp.match(/\(/g) || []).length;
  var rightBracketNum = (exp.match(/\)/g) || []).length;
  var ruleConNo = /\s*\d+\s+\d+\s*/g.test(exp);
  var ruleConLogic = /\s*(AND|OR)\s*(AND|OR)\s*/g.test(exp);
  var illegalChar = /^(?!AND|OR|\(|\)|\d)/g.test(exp);
  if (leftBracketNum !== rightBracketNum || ruleConNo || ruleConLogic || illegalChar) return true;
  return false;
}

function calculateExpression(conditionList, _ref7) {
  var getValueFromCache = _ref7.getValueFromCache,
      _ref7$currentUnitCode = _ref7.currentUnitCode,
      currentUnitCode = _ref7$currentUnitCode === void 0 ? '' : _ref7$currentUnitCode,
      isGrid = _ref7.isGrid,
      code = _ref7.code,
      isGridVisible = _ref7.isGridVisible,
      others = _objectWithoutProperties(_ref7, _excluded3);

  var result = {};
  conditionList.forEach(function (i) {
    var conCode = i.conCode,
        _i$sourceFieldCode = i.sourceFieldCode,
        sourceFieldCode = _i$sourceFieldCode === void 0 ? '' : _i$sourceFieldCode,
        sourceUnitCode = i.sourceUnitCode,
        conExpression = i.conExpression,
        targetType = i.targetType,
        _i$targetFieldCode = i.targetFieldCode,
        targetFieldCode = _i$targetFieldCode === void 0 ? '' : _i$targetFieldCode,
        targetValue = i.targetValue;
    if (!sourceUnitCode || !sourceFieldCode) return result;

    if (isGridVisible && (currentUnitCode === sourceUnitCode || targetType === 'formNow')) {
      result[conCode] = true;
      return result;
    }

    var left;
    var right = targetValue;
    var targetForm = others.targetForm,
        targetDataSource = others.targetDataSource;

    var targetAllValue = _objectSpread(_objectSpread({}, targetDataSource), targetForm ? targetForm.getFieldsValue() : {});

    if (isGrid && currentUnitCode === sourceUnitCode) {
      left = targetAllValue[sourceFieldCode];
    } else {
      left = getValueFromCache(sourceUnitCode, sourceFieldCode);
    }

    if (isGrid && targetType === 'formNow') {
      if (!targetFieldCode) return result;
      right = targetAllValue[targetFieldCode];
    } else if (targetType === 'formNow') {
      right = getValueFromCache(code, targetFieldCode);
    }

    result[conCode] = logicCompute(conExpression, left, right);
  });
  return result;
}

export function getContextParams() {
  var paramList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var options = arguments.length > 1 ? arguments[1] : undefined;

  var _ref8 = options || {},
      _ref8$getValueFromCac = _ref8.getValueFromCache,
      getValueFromCache = _ref8$getValueFromCac === void 0 ? function () {} : _ref8$getValueFromCac,
      isGrid = _ref8.isGrid,
      form = _ref8.form,
      dataSource = _ref8.dataSource,
      isConfig = _ref8.isConfig,
      code = _ref8.code;

  var paramObj = {};
  var search = window.location.search;
  var urlParams = {};

  if (search) {
    search.substr(1).split('&').forEach(function (item) {
      if (item) {
        var _item$split = item.split('='),
            _item$split2 = _slicedToArray(_item$split, 2),
            key = _item$split2[0],
            value = _item$split2[1];

        urlParams[key] = value;
      }
    });
  }

  var c = getContext();
  paramList.forEach(function (item) {
    if (item.paramType === 'context') {
      switch (item.paramValue) {
        case 'organizationId':
          paramObj[item.paramKey] = c.organizationId;
          break;

        case 'tenantId':
          paramObj[item.paramKey] = c.tenantId;
          break;

        default:
      }
    } else if (item.paramType === 'url') {
      paramObj[item.paramKey] = urlParams[item.paramKey];
    } else if (item.paramType === 'fixed') {
      paramObj[item.paramKey] = item.paramValue;
    } else if (!isConfig) {
      // eslint-disable-next-line prefer-const
      var value = getValueFromCache(item.paramUnitCode, item.paramFieldCode);

      if (isGrid && code === item.paramUnitCode) {
        value = _objectSpread(_objectSpread({}, dataSource), form ? form.getFieldsValue() : {})[item.paramFieldCode || ''];
      }

      paramObj[item.paramKey] = value;
    }
  });
  return paramObj;
}

function logicCompute(type, left, right) {
  switch (type) {
    case '=':
      return left == right;

    case '>=':
      return left >= right;

    case '<=':
      return left <= right;

    case '!=':
      return left != right;

    case '>':
      return left > right;

    case '<':
      return left < right;

    case 'ISNULL':
      return left === undefined || left === null;

    case 'NOTNULL':
      return left !== undefined && left !== null;

    case 'BEFORE':
      return moment(left).isBefore(moment(right));

    case 'SAME':
      return moment(left).isSame(moment(right));

    case 'NOTSAME':
      return !moment(left).isSame(moment(right));

    case 'AFTER':
      return moment(left).isAfter(moment(right));

    case '~BEFORE':
      return !moment(left).isBefore(moment(right));

    case '~AFTER':
      return !moment(left).isAfter(moment(right));

    case 'LIKE':
      return new RegExp(right, 'g').test(String(left));

    case 'UNLIKE':
      return !new RegExp(right, 'g').test(String(left));

    case '~LIKE':
      return new RegExp(right, 'g').test(String(left));

    case '~UNLIKE':
      return !new RegExp(right, 'g').test(String(left));

    default:
      return false;
  }
}

export function getFieldValueObject() {
  var relatedList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var getCache = arguments.length > 1 ? arguments[1] : undefined;
  var code = arguments.length > 2 ? arguments[2] : undefined;
  var obj = {
    c: getContext()
  };
  relatedList.forEach(function (_ref9) {
    var unitCode = _ref9.unitCode,
        alias = _ref9.alias;
    var newAlias = unitCode === code ? 'self' : alias;

    var _getCache = getCache(unitCode),
        form = _getCache.form,
        dataSource = _getCache.dataSource;

    obj[newAlias] = _objectSpread(_objectSpread({}, dataSource), form && form.getFieldsValue());
  });
  return obj;
}
export function getComputeComp(renderRule, options) {
  var wrapProps = options.wrapProps,
      _options$unitData = options.unitData,
      unitData = _options$unitData === void 0 ? {} : _options$unitData,
      isGrid = options.isGrid,
      form = options.form,
      dataSource = options.dataSource;

  if (isGrid) {
    // eslint-disable-next-line no-param-reassign
    unitData.self = _objectSpread(_objectSpread({}, dataSource), form && form.getFieldsValue());
    return /*#__PURE__*/React.createElement("div", {
      dangerouslySetInnerHTML: {
        __html: template.render(renderRule, unitData)
      }
    });
  }

  return /*#__PURE__*/React.createElement(FormItem, wrapProps, /*#__PURE__*/React.createElement("div", {
    dangerouslySetInnerHTML: {
      __html: template.render(renderRule, unitData)
    }
  }));
}
export function getContext() {
  return {
    organizationId: getCurrentOrganizationId(),
    tenantId: getUserOrganizationId()
  };
}
export function selfValidator(conValid, config) {
  var _ref10 = conValid || {},
      _ref10$conLineList = _ref10.conLineList,
      conLineList = _ref10$conLineList === void 0 ? [] : _ref10$conLineList,
      _ref10$conValidList = _ref10.conValidList,
      conValidList = _ref10$conValidList === void 0 ? [] : _ref10$conValidList;

  conLineList = _isArray(conLineList) ? conLineList : [];
  conValidList = _isArray(conValidList) ? conValidList : [];
  var result = calculateExpression(conLineList, config);
  var validation = [];
  conValidList.forEach(function (i) {
    var newExpression = i.conExpression || '';
    var isErr = isErrConExpression(newExpression);

    if (!isErr) {
      var conNoReg = /(\d+)/g;
      newExpression = newExpression.replace(conNoReg, function (_, m) {
        return result[m] || false;
      });
      newExpression = newExpression.replace(/AND/g, '&&').replace(/OR/g, '||'); // eslint-disable-next-line no-new-func

      validation.push({
        // eslint-disable-next-line no-new-func
        isCorrect: new Function("return ".concat(newExpression, ";"))(),
        message: i.errorMessage
      });
    }
  });

  if (validation.length > 0) {
    return {
      customize: true,
      // eslint-disable-next-line no-unused-vars
      validator: function validator(_, _1, cb) {
        for (var i = 0; i < validation.length; i += 1) {
          if (!validation[i].isCorrect) {
            cb(validation[i].message); // eslint-disable-next-line no-useless-return

            return;
          }
        }

        cb();
      }
    };
  }

  return {};
}